package com.zucai365.football.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ActionSupport;
import com.zucai365.football.bean.CurrentFootballTeamBean;
import com.zucai365.football.bean.GameFireBean;
import com.zucai365.football.bean.LianSaiBean;
import com.zucai365.football.bean.LianSaiInfoBean;
import com.zucai365.football.bean.LianSaiYearBean;
import com.zucai365.football.bean.ShouFaBean;
import com.zucai365.football.bean.TeamDZBean;
import com.zucai365.football.bean.TeamDzErrorLogBean;
import com.zucai365.football.service.CurrentFootballTeamService;
import com.zucai365.football.service.FootballPlayerService;
import com.zucai365.football.service.FootballTeamService;
import com.zucai365.football.service.GameFireService;
import com.zucai365.football.service.LianSaiInfoService;
import com.zucai365.football.service.ShouFaService;
import com.zucai365.football.service.TeamDZService;
import com.zucai365.football.service.TeamDzErrorLogService;
import com.zucai365.football.utils.Constant;
import com.zucai365.football.utils.DateUtils;
import com.zucai365.football.utils.ZuCaiUtils;

public class TeamAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6469826427886249286L;
	
	/**
	 * 当前赛季ID
	 */
	private Long lianSaiYearId;
	
	public Long getLianSaiYearId() {
		return lianSaiYearId;
	}

	public void setLianSaiYearId( Long lianSaiYearId ) {
		this.lianSaiYearId = lianSaiYearId;
	}
	/**
	 * 联赛ID
	 */
	private Long lianSaiId;
	
	public Long getLianSaiId() {
		return lianSaiId;
	}

	public void setLianSaiId(Long lianSaiId) {
		this.lianSaiId = lianSaiId;
	}
	
	/**
	 * 当前赛季球队ID
	 */
	private Long currentFootballTeamId;
	
	public Long getCurrentFootballTeamId() {
		return currentFootballTeamId;
	}

	public void setCurrentFootballTeamId(Long currentFootballTeamId) {
		this.currentFootballTeamId = currentFootballTeamId;
	}
	
	private Integer lunci;
	
	public Integer getLunci() {
		return lunci;
	}

	public void setLunci( Integer lunci ) {
		this.lunci = lunci;
	}
	
	@Autowired
	@Qualifier("currentFootballTeamService")
	private CurrentFootballTeamService currentFootballTeamService;
	
	public CurrentFootballTeamService getCurrentFootballTeamService() {
		return currentFootballTeamService;
	}

	public void setCurrentFootballTeamService(
			CurrentFootballTeamService currentFootballTeamService) {
		this.currentFootballTeamService = currentFootballTeamService;
	}
	
	public String list(){
		
		ServletActionContext.getRequest().setAttribute( "lianSaiYearList", Constant.ALL_LIANSAI_YEAR_LIST );
		ServletActionContext.getRequest().setAttribute( "lianSaiList", Constant.ALL_LIANSAI_LIST );
		if( this.lianSaiYearId == null ){
			this.lianSaiYearId = ZuCaiUtils.CURRENT_LIANSAI_YEAR;
		}
		if( this.lianSaiId == null ){
			this.lianSaiId = ZuCaiUtils.CURRENT_LIANSAI;
		}
		
		List<CurrentFootballTeamBean> teamList = this.currentFootballTeamService.getCurrentFootballTeamList( this.lianSaiId, this.lianSaiYearId);
		ServletActionContext.getRequest().setAttribute( "teamList", teamList );
		return "list";
	}
	
	@Autowired
	@Qualifier("footballPlayerService")
	private FootballPlayerService footballPlayerService;
	
	public FootballPlayerService getFootballPlayerService() {
		return footballPlayerService;
	}

	public void setFootballPlayerService(FootballPlayerService footballPlayerService) {
		this.footballPlayerService = footballPlayerService;
	}

	/**
	 * 保存球员信息
	 * @return
	 */
	public String savePlayer(){
		
		//下载球队球员json字符串
		CurrentFootballTeamBean currentFootballTeam = this.currentFootballTeamService.get( this.currentFootballTeamId );
		ZuCaiUtils.dowloadTeamPlayerJS( currentFootballTeam );
		
		this.footballPlayerService.saveFootplayer( lianSaiYearId, lianSaiId, currentFootballTeam.getFootballTeam().getId() );
		
		return "listPage";
	}
	
	/**
	 * 批量保存球员信息
	 * @return
	 */
	public String saveTeamAllPlayer(){
		
		String[] teamIds = ServletActionContext.getRequest().getParameterValues( "teamIds" );
		
		for( String teamId : teamIds ){
			CurrentFootballTeamBean currentFootballTeam = this.currentFootballTeamService.get( 	Long.valueOf( teamId ) );
			ZuCaiUtils.dowloadTeamPlayerJS( currentFootballTeam );			
			this.footballPlayerService.saveFootplayer( lianSaiYearId, lianSaiId, currentFootballTeam.getFootballTeam().getId() );
		}
		
		return "listPage";
	}
	
	@Autowired
	@Qualifier("teamDZService")
	private TeamDZService teamDZService;
	
	public TeamDZService getTeamDZService() {
		return teamDZService;
	}

	public void setTeamDZService(TeamDZService teamDZService) {
		this.teamDZService = teamDZService;
	}

	/**
	 * 查询球队对阵信息
	 * @return
	 */
	public String dzInfo(){
		
		ServletActionContext.getRequest().setAttribute( "lianSaiYearList", Constant.ALL_LIANSAI_YEAR_LIST );
		ServletActionContext.getRequest().setAttribute( "lianSaiList", Constant.ALL_LIANSAI_LIST );
		
		
		if( this.lianSaiYearId == null ){
			this.lianSaiYearId = ZuCaiUtils.CURRENT_LIANSAI_YEAR;
		}
		
		if( this.lianSaiId == null ){
			this.lianSaiId = ZuCaiUtils.CURRENT_LIANSAI;			
		}
		
		ServletActionContext.getRequest().setAttribute( "sumLunci", ZuCaiUtils.getLianSaiById( this.lianSaiId ).getSumLunci()+"" );
		
		if( this.lunci == null ){
			this.lunci = 1;
		}
		
		ServletActionContext.getRequest().setAttribute( "teamDZList", this.teamDZService.getTeamDzList(lianSaiId, lianSaiYearId, lunci) );
		return "teamDZList";
	}
	
	@Autowired
	@Qualifier("lianSaiInfoService")
	private LianSaiInfoService lianSaiInfoService;
	
	public LianSaiInfoService getLianSaiInfoService() {
		return lianSaiInfoService;
	}

	public void setLianSaiInfoService(LianSaiInfoService lianSaiInfoService) {
		this.lianSaiInfoService = lianSaiInfoService;
	}
	
	@Autowired
	@Qualifier("footballTeamService")
	private FootballTeamService footballTeamService;
	
	public FootballTeamService getFootballTeamService() {
		return footballTeamService;
	}

	public void setFootballTeamService(FootballTeamService footballTeamService) {
		this.footballTeamService = footballTeamService;
	}

	/**
	 * 采集每轮比赛的球队对阵数据
	 * @return
	 */
	public String cjTeamDzData(){
		
		//下载该联赛的对阵数据
		ZuCaiUtils.dowloadTeamJs( this.lianSaiInfoService.getLianSaiInfo(lianSaiId, lianSaiYearId).get(0) );
		
		//获取当前轮次对阵JSON串
		LianSaiBean liansai = ZuCaiUtils.getLianSaiById( this.lianSaiId );
		LianSaiYearBean liansaiYear = ZuCaiUtils.getLianSaiYearById( this.lianSaiYearId );	
		String teamDZJson = ZuCaiUtils.getTeamDZJson( liansai, liansaiYear , this.lunci );
			
		JSONArray jsonArray = JSONArray.fromObject( teamDZJson );
		for( int i=0;i<jsonArray.size();i++ ){
			JSONArray teamDZArray = (JSONArray)jsonArray.get(i);
			
			String playId = teamDZArray.getString(0);
			
			//比赛时间
			String playTime = teamDZArray.getString( 3 );
			
			TeamDZBean teamDZ = this.teamDZService.getTeamDZBean( playId );
			
			teamDZ.setPlayTime( DateUtils.formatTimestamp( playTime ) );
			
			String bifen = teamDZArray.getString( 6 );
			
			//上半场比分
			String sbcBifen = teamDZArray.getString( 7 );
			
			//亚盘初盘
			String yapan = teamDZArray.getString( 10 );
			
			//大小球
			String daxiaoQiu = teamDZArray.getString( 12 );
			
			teamDZ.setSbcSource( sbcBifen );
			teamDZ.setYapan(yapan);
			teamDZ.setDaxiaoQiu(daxiaoQiu);
			
			
			
			if( StringUtils.isNotBlank( bifen ) && bifen.indexOf( "-" ) >-1 ){
				teamDZ.setSource( bifen );
				String[] temps = bifen.split( "-" );
				if( Integer.parseInt( temps[0] ) > Integer.parseInt( temps[1] ) ){
					teamDZ.setResult( "胜" );
					teamDZ.setZdJifen(3);
					teamDZ.setKdJifen(0);	
				}else if( Integer.parseInt( temps[0] ) < Integer.parseInt( temps[1] )  ){
					teamDZ.setResult( "负" );
					teamDZ.setZdJifen(0);
					teamDZ.setKdJifen(3);
				}else{
					teamDZ.setResult( "平" );
					teamDZ.setZdJifen(1);
					teamDZ.setKdJifen(1);
				}
				teamDZ.setCjStatus( "已采集" );
				
				try {
					String content = ZuCaiUtils.getUrlContent( teamDZ.getUrlBet007(), "gbk" );
					
					Document doc = Jsoup.parse( content );
					Elements elements = doc.getElementsByTag( "table" );
					
					teamDZ.setGameFireHtml( elements.get(0).toString() );
					teamDZ.setJstjHtml( elements.get(4).toString() );
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
			this.teamDZService.saveOrUpdate( teamDZ );
		}
		
		return "teamDZPage";
		
	}
	
	private Long teamDZId;
	
	public Long getTeamDZId() {
		return teamDZId;
	}

	public void setTeamDZId(Long teamDZId) {
		this.teamDZId = teamDZId;
	}

	/**
	 * 采集一场比赛的对阵数据
	 * @return
	 */
	public String cjOneGameData(){
		
		//下载该联赛的对阵数据
		ZuCaiUtils.dowloadTeamJs( this.lianSaiInfoService.getLianSaiInfo(lianSaiId, lianSaiYearId).get(0) );
		
		//当前比赛
		TeamDZBean teamDZ = this.teamDZService.get( this.teamDZId );
		
		//获取当前轮次对阵JSON串
		LianSaiBean liansai = ZuCaiUtils.getLianSaiById( this.lianSaiId );
		LianSaiYearBean liansaiYear = ZuCaiUtils.getLianSaiYearById( this.lianSaiYearId );	
		String teamDZJson = ZuCaiUtils.getTeamDZJson( liansai, liansaiYear , this.lunci );
			
		JSONArray jsonArray = JSONArray.fromObject( teamDZJson );
		for( int i=0;i<jsonArray.size();i++ ){
			JSONArray teamDZArray = (JSONArray)jsonArray.get(i);
			
			String playId = teamDZArray.getString(0);
			//如果比赛ID不一样， 返回重新查找
			if( !playId.equals( teamDZ.getPlayId() ) ){
				continue;
			}
					
			//比赛时间
			String playTime = teamDZArray.getString( 3 );
						
			teamDZ.setPlayTime( DateUtils.formatTimestamp( playTime ) );
			
			String bifen = teamDZArray.getString( 6 );
			
			//上半场比分
			String sbcBifen = teamDZArray.getString( 7 );
			
			//亚盘初盘
			String yapan = teamDZArray.getString( 10 );
			
			//大小球
			String daxiaoQiu = teamDZArray.getString( 12 );
			
			teamDZ.setSbcSource( sbcBifen );
			teamDZ.setYapan(yapan);
			teamDZ.setDaxiaoQiu(daxiaoQiu);
					
			if( StringUtils.isNotBlank( bifen ) && bifen.indexOf( "-" ) >-1 ){
				teamDZ.setSource( bifen );
				String[] temps = bifen.split( "-" );
				if( Integer.parseInt( temps[0] ) > Integer.parseInt( temps[1] ) ){
					teamDZ.setResult( "胜" );
					teamDZ.setZdJifen(3);
					teamDZ.setKdJifen(0);	
				}else if( Integer.parseInt( temps[0] ) < Integer.parseInt( temps[1] )  ){
					teamDZ.setResult( "负" );
					teamDZ.setZdJifen(0);
					teamDZ.setKdJifen(3);
				}else{
					teamDZ.setResult( "平" );
					teamDZ.setZdJifen(1);
					teamDZ.setKdJifen(1);
				}
				teamDZ.setCjStatus( "已采集" );
				
				try {
					String content = ZuCaiUtils.getUrlContent( teamDZ.getUrlBet007(), "gbk" );
					
					Document doc = Jsoup.parse( content );
					Elements elements = doc.getElementsByTag( "table" );
					
					teamDZ.setGameFireHtml( elements.get(0).toString() );
					teamDZ.setJstjHtml( elements.get(4).toString() );
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
			this.teamDZService.saveOrUpdate( teamDZ );
		}
		
		return "teamDZPage";
		
	}
	
	@Autowired
	@Qualifier("shouFaService")
	private ShouFaService shouFaService;
	
	public ShouFaService getShouFaService() {
		return shouFaService;
	}

	public void setShouFaService(ShouFaService shouFaService) {
		this.shouFaService = shouFaService;
	}

	/**
	 * 统计每轮比赛的首发，红黄牌，进球情况
	 * @return
	 */
	public String jstjTeamDzData(){
		
		List<TeamDZBean> teamDZList = this.teamDZService.getTeamDzList(lianSaiId, lianSaiYearId, lunci) ;
		
		List<ShouFaBean> shuofaList = new ArrayList<ShouFaBean>();
		List<GameFireBean> gameFireList = new ArrayList<GameFireBean>();
		
		for( TeamDZBean teamDZ : teamDZList ){
			
			String msg = teamDZ.getGameFireHtml();
			
			if( StringUtils.isBlank( msg ) ){
				continue;
			}
			
			msg = msg.replace( "width=\"99%\"", "width=\"100%\"" );
			msg = msg.replace( "width=\"100%\"", "width=\"100%\" class=\"zucaiClass\" " );
			
			Document doc = Jsoup.parse( msg );
			Elements elements = doc.getElementsByClass( "zucaiClass" );
			
			//首发情况
			String zdShouFa = elements.get(0).toString() ;
			String kdShouFa = elements.get(2).toString() ;
			
			shuofaList.addAll( ZuCaiUtils.parseShouFa( zdShouFa , teamDZ, teamDZ.getZd() ) );
			shuofaList.addAll( ZuCaiUtils.parseShouFa( kdShouFa , teamDZ , teamDZ.getKd() ) );
			
			gameFireList.addAll( ZuCaiUtils.parseGameFire( msg, teamDZ, teamDZ.getZd(), teamDZ.getKd() ) );
			
			teamDZ.setTjStatus( "已统计" );
		}
		
		this.shouFaService.saveGameFireInfo(shuofaList,gameFireList);
		this.teamDZService.saveAll( teamDZList );
		return "teamDZPage";
		
	}
	
	/**
	 * 统计每场比赛的首发，红黄牌，进球情况
	 * @return
	 */
	public String jstjOneTeamDzData(){
		
	
		List<ShouFaBean> shuofaList = new ArrayList<ShouFaBean>();
		List<GameFireBean> gameFireList = new ArrayList<GameFireBean>();
		
		TeamDZBean teamDZ = this.teamDZService.get( teamDZId );
		String lunciFlag = "jh[\"R_"+teamDZ.getLunci()+"\"]" ;
		
		//下载每个赛季的对阵信息
		LianSaiInfoBean lianSaiInfo = this.lianSaiInfoService.getLianSaiInfo( lianSaiId, lianSaiYearId ).get(0);
		ZuCaiUtils.dowloadTeamJs(lianSaiInfo);
		
		String jspath = Constant.WAR_PATH + "teamInfo/" + lianSaiInfo.getLianSai().getEnglishName() + "/" + lianSaiInfo.getLianSaiYear().getLiansaiYear() + ".js" ;
		
		File jsFile = new File( jspath );
		FileInputStream stream = null;
		InputStreamReader reader = null;
		BufferedReader br = null;
			
		try {
			stream = new FileInputStream( jsFile );
			reader = new InputStreamReader( stream, "utf-8" );
			br = new BufferedReader( reader );		
			
			String teamDZJson = "";
			while (( teamDZJson = br.readLine()) != null ) {			
				if( teamDZJson.startsWith( lunciFlag )){					
					break;
				}
			}
					
			String[] json = teamDZJson.split( "=" );		
			String dzData =json[1].trim();
			dzData = dzData.substring(0,dzData.length()-1 );
			
			JSONArray jsonArray = JSONArray.fromObject( dzData );
			for( int i=0;i<jsonArray.size();i++ ){
				JSONArray teamDZArray = (JSONArray)jsonArray.get(i);				
				String playId = teamDZArray.getString(0);
				String playTime = teamDZArray.getString(3);
				String url = "http://bf.bet007.com/detail/"+playId+"cn.htm";
				if( url.equals( teamDZ.getUrlBet007() ) ){
					teamDZ.setPlayTime( DateUtils.formatTimestamp( playTime ) );
					break;
				}
				
			}
			
		} catch ( Exception e) {
			throw new RuntimeException( e.getCause() );
		}finally{
			try {
				stream.close();
				reader.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		String msg = teamDZ.getGameFireHtml();
		
		if( StringUtils.isBlank( msg ) ){
			return "teamDZPage";
		}
		
		msg = msg.replace( "width=\"99%\"", "width=\"100%\"" );
		msg = msg.replace( "width=\"100%\"", "width=\"100%\" class=\"zucaiClass\" " );
		
		Document doc = Jsoup.parse( msg );
		Elements elements = doc.getElementsByClass( "zucaiClass" );
		
		//首发情况
		String zdShouFa = elements.get(0).toString() ;
		String kdShouFa = elements.get(2).toString() ;
		
		shuofaList.addAll( ZuCaiUtils.parseShouFa( zdShouFa , teamDZ, teamDZ.getZd() ) );
		shuofaList.addAll( ZuCaiUtils.parseShouFa( kdShouFa , teamDZ , teamDZ.getKd() ) );
		
		gameFireList.addAll( ZuCaiUtils.parseGameFire( msg, teamDZ, teamDZ.getZd(), teamDZ.getKd() ) );
		
		teamDZ.setTjStatus( "已统计" );
		
		this.shouFaService.saveGameFireInfo(shuofaList,gameFireList);
		this.teamDZService.saveOrUpdate( teamDZ );
		
		return "teamDZPage";
		
	}
	
	@Autowired
	@Qualifier("gameFireService")
	private GameFireService gameFireService;
	
	public GameFireService getGameFireService() {
		return gameFireService;
	}

	public void setGameFireService(GameFireService gameFireService) {
		this.gameFireService = gameFireService;
	}
	
	@Autowired
	@Qualifier("teamDzErrorLogService")
	private TeamDzErrorLogService teamDzErrorLogService;
	
	public TeamDzErrorLogService getTeamDzErrorLogService() {
		return teamDzErrorLogService;
	}

	public void setTeamDzErrorLogService(TeamDzErrorLogService teamDzErrorLogService) {
		this.teamDzErrorLogService = teamDzErrorLogService;
	}

	public String viewTeamDzData(){
		
		//
		TeamDZBean teamDZ = this.teamDZService.get( teamDZId );
		
		List<ShouFaBean> shouFaList = this.shouFaService.searchShouFa( teamDZ.getId() , null);
				
		//todo 1,统计首发，2，统计比赛详细 3，查询本次比赛错误日志
		
		List<GameFireBean> gameFireList = this.gameFireService.searchGameFire( teamDZ.getId() , null);
		
		List<TeamDzErrorLogBean> teamDzErrorLogList = this.teamDzErrorLogService.searchTeamDzErrorLog( teamDZ.getId() );
		
		ServletActionContext.getRequest().setAttribute( "teamDZ", teamDZ );
		ServletActionContext.getRequest().setAttribute( "shouFaList", shouFaList );
		ServletActionContext.getRequest().setAttribute( "gameFireList", gameFireList );
		ServletActionContext.getRequest().setAttribute( "teamDzErrorLogList", teamDzErrorLogList );
		
		return "gamefire_info";
		
	}
}
